library(xts)
library(here)
Creating Time Series Index in R
Introduction
This tutorial will guide you through the process of creating a time series index using R, using exchange rate data as an example.
Load Required Libraries
First, let’s load the necessary libraries. The xts
package is essential for working with time series data, and here
helps in managing file paths.
Load Time Series Data
For this tutorial, we’ll use the dataset euro
, which contains exchange rate data.
<- readRDS(here("databases/euro.rds")) # Load your dataset here euro
Let’s visualize the Euro to USD exchange rate:
plot.zoo(euro$XUS, main = "Euro-Dollar Exchange Rate", las = 1, xlab = "", ylab = "")
Calculate the Index
To calculate an index with a specific reference date (e.g., February 28, 2020) set to 100, we use the following formula:
$iXUS <- 100 * euro$XUS / drop(coredata(euro$XUS["2020-02-28"])) euro
Explanation
- Creating a New Variable:
euro$iXUS
- This line creates a new variable
iXUS
in theeuro
dataset to store the index values.
- This line creates a new variable
- Calculating the Ratio:
100 * euro$XUS
- This part scales the exchange rate data so that the value on the reference date (February 28, 2020) is 100. It does so by multiplying each data point by 100.
- Dividing by the Reference Value:
/ drop(coredata(euro$XUS["2020-02-28"]))
- This part normalizes the data to the reference date.
euro$XUS["2020-02-28"]
extracts the exchange rate on February 28, 2020.coredata()
extracts the core value from the time series object.drop()
ensures that the result is a single numeric value, not a time series object.
Putting it all together, this calculation scales the exchange rate values so that they are relative to the exchange rate on February 28, 2020, which is set to 100.
Plot the Index
We can now visualize the calculated index using a time series plot. This allows us to see how the exchange rate has changed relative to our reference date.
plot.zoo(euro$iXUS, las = 1, main = "Euro-Dollar Exchange Rate Index", xlab = "", ylab = "")
abline(h = 100, col = "red", lty = 2) # Adding a reference line at 100
This plot shows the index, with a red dashed line at 100 representing the reference point.
Summary
In this tutorial, we demonstrated how to create a time series index in R, using exchange rate data.